package com.xiaoyu.lanling.feature.login.fragment

import `in`.srain.cube.util.UTUtil
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.data.ConfigData
import com.xiaoyu.lanling.event.login.LoginCellphoneClickNextEvent
import com.xiaoyu.lanling.event.login.LoginCellphoneClickWechatLoginEvent
import com.xiaoyu.lanling.router.deeplink.DeepLinkRouter
import com.xiaoyu.lanling.view.OnShowFragment
import com.xiaoyu.lanling.view.listener.BaseTextWatcher
import kotlinx.android.synthetic.main.fragment_login_cellphone.*

class LoginCellphoneFragment : OnShowFragment() {

    companion object {
        fun newInstance(): LoginCellphoneFragment {
            return LoginCellphoneFragment()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_login_cellphone, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initBind()
        logEvent()
    }

    private fun logEvent() {
        UTUtil.getInstance().logEvent("login_mobile_enter")
    }

    private fun initBind() {
        edit_text.addTextChangedListener(object : BaseTextWatcher() {
            override fun afterTextChanged(s: Editable?) {
                val valid = s?.length == 11
                next.isEnabled = valid

                if (valid) {
                    KeyboardUtil.hideKeyboard(edit_text)
                }
            }
        })
        next.setOnClickDebounceListener {
            LoginCellphoneClickNextEvent(edit_text.text.toString()).post()
        }
        wechat_login_button.setOnClickDebounceListener {
            activity?.finish()
            LoginCellphoneClickWechatLoginEvent().post()
        }
        user_text.setOnClickDebounceListener {
            context?.let {
                val url = ConfigData.getInstance().getUrl("userProtocol")
                DeepLinkRouter.getInstance().dispatch(it, url)
            }
        }
        privacy_text.setOnClickDebounceListener {
            context?.let {
                val url = ConfigData.getInstance().getUrl("privacyProtocol")
                DeepLinkRouter.getInstance().dispatch(it, url)
            }
        }
    }
}